package com.tofix.kidmall.service.impl;

import com.tofix.kidmall.common.CommonPage;
import com.tofix.kidmall.common.CommonResult;
import com.tofix.kidmall.entity.Role;
import com.tofix.kidmall.entity.User;
import com.tofix.kidmall.exception.ApiExcetion;
import com.tofix.kidmall.repo.RoleRepo;
import com.tofix.kidmall.repo.UserRepo;
import com.tofix.kidmall.service.RoleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;
import java.util.Set;

@Service
@Transactional(rollbackFor = Exception.class)
public class RoleServiceImpl implements RoleService {
    private final static Logger logger = LoggerFactory.getLogger(RoleServiceImpl.class);

    @Autowired
    RoleRepo roleRepo;
//    @Autowired
//    private UserRepo userRepo;

    @Override
    @Cacheable(cacheNames = "role")
    public Optional<Role> getById(String id){
        return roleRepo.findById(id);
    }

    @Override
    public Role insertRole(Role role){
//        Set<User> userSet = role.getUserSet();
//
//        userSet.forEach(user -> {
//            User serach = userRepo.findUserById(user.getUserId());
//        });
        return roleRepo.save(role);
    }

    @Override
    public void deleteRole(String id) throws ApiExcetion{
        try {
            roleRepo.deleteById(id);
        } catch (Exception e) {
            logger.debug(e.getMessage());
            throw new ApiExcetion("没有该主键");
        }
    }

    @Override
    public Role saveRole(Role role){
        return roleRepo.save(role);
    }

    @Override
    public CommonPage<Role> getAllByPage(Integer currentPage, Integer pageSize) {
        return CommonPage.restPage(roleRepo.findAll(PageRequest.of(currentPage, pageSize)));
    }

    @Override
    public CommonResult<List<Role>> getAll() {
        return CommonResult.success(roleRepo.findAll());
    }

}
